package captcha

import (
	"context"
	"errors"
	"github.com/vueadmin/global"
	"strconv"
	"time"
)

const CAPTCHA = "captcha:"

type RedisStore struct{}

func (r RedisStore) Set(id string, value string) error {
	v, _ := strconv.Atoi(value)
	if err := global.REDIS.Set(context.Background(), CAPTCHA+id, v, 180*time.Second).Err(); err != nil {
		return errors.New("设置失败")
	}
	return nil
}

func (r RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	res := global.REDIS.Get(context.Background(), key)

	if clear {
		global.REDIS.Del(context.Background(), key)
	}

	return res.Val()
}

func (r RedisStore) Verify(id, answer string, clear bool) bool {
	v := RedisStore{}.Get(id, clear)
	return v == answer
}
